package com.jy.appmarket.activity;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.database.ContentObserver;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jy.app.market.apk.type.LinkType;
import com.jy.app.market.idata.card.CardWords;
import com.jy.app.market.idata.data.Download;
import com.jy.app.market.idata.data.Drift;
import com.jy.app.market.idata.data.EscRecommend;
import com.jy.app.market.idata.data.Link;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.dialog.EscRecommendDialog;
import com.jy.appmarket.download.DownloadActivity;
import com.jy.appmarket.download.DownloadItem;
import com.jy.appmarket.download.DownloadUtils;
import com.jy.appmarket.fragment.FragmentApps;
import com.jy.appmarket.fragment.FragmentDiscovery;
import com.jy.appmarket.fragment.FragmentGames;
import com.jy.appmarket.fragment.FragmentRank;
import com.jy.appmarket.fragment.HomeMenuFragment;
import com.jy.appmarket.network.engine.BaseNetEngine;
import com.jy.appmarket.network.engine.DriftNetEngine;
import com.jy.appmarket.network.engine.EscRecommendNetEngine;
import com.jy.appmarket.network.engine.cachestrategy.CacheStrategy;
import com.jy.appmarket.network.engine.cachestrategy.NamedCacheStrategy;
import com.jy.appmarket.network.resultdata.DriftResult;
import com.jy.appmarket.network.resultdata.EscRecommendResult;
import com.jy.appmarket.network.resultdata.HotWordsResultData;
import com.jy.appmarket.network.task.NetTask;
import com.jy.appmarket.network.task.NetTask.NetTaskListener;
import com.jy.appmarket.statistics.ApkSource;
import com.jy.appmarket.statistics.event.showDriftIconEvent;
import com.jy.appmarket.statistics.event.showEscRecommendEvent;
import com.jy.appmarket.statistics.umeng.myUmengStaticstics;
import com.jy.appmarket.utils.ActivateStatistics;
import com.jy.appmarket.utils.AdManager;
import com.jy.appmarket.utils.AndroidUtil;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.view.PagerSlidingTabStrip;
import com.mikepenz.actionitembadge.library.ActionItemBadge;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.rad.statistics.android.StatisticsAgent;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.jy.appmarket.fragment.HomeMenuFragment.REQUEST_LOGIN_CODE;
import static com.jy.appmarket.fragment.HomeMenuFragment.REQUEST_LOGOUT_CODE;

public class MainActivity extends DownloadActivity implements NetTaskListener {
	private static final String TAG = MainActivity.class.getSimpleName();
	private DrawerLayout mainDrawer;
	private LinearLayout llMainSide;
	private ViewPager mViewPager;
	private PagerSlidingTabStrip mTabStrip;
	private Fragment mFragmentDiscovery;
	private Fragment mFragmentRank;
	private Fragment mFragmentGame;
	private Fragment mFragmentApp;
	private HomeMenuFragment homeMenuFragment;
	private long mLastClickBackTime;

	private NetTask mNetTask;
	private NetTask mNetTask2;
	private Drift mDrift = null;
	private EscRecommend mEscRecommend = null;
	private Bitmap mEscRecommendBannerImage = null;
	private int mDriftDataRetryCount = 0;
	private int mEscRecommenDataRetryCount = 0;
	private EscRecommendDialog mEscRecommendDialog;

	private int mUnFinished = Integer.MIN_VALUE;
	private int mUpdateCount = Integer.MIN_VALUE;
	private boolean mDestroyed = false;

	private ImageView mDriftView;
	private Handler mHandler = new Handler();

	private ContentObserver mContentObserver = new ContentObserver(new Handler()) {
		@Override
		public void onChange(boolean selfChange) {
			invalidateUpdateBadgeIfNeeded();
		}

		@Override
		public void onChange(boolean selfChange, Uri uri) {
			invalidateUpdateBadgeIfNeeded();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
//		initTitle();
		initDrawer();
		initViewPager();
		initTabStrip();

		loadDriftData();
		loadEscRecommendData();

		invalidateDownloadBadgeIfNeeded();
		invalidateUpdateBadgeIfNeeded();
		mDestroyed = false;

		getContentResolver().registerContentObserver(AppUpdateDatabase.URI, false, mContentObserver);

		ActivateStatistics.ActivateFrom(this, this.getClass().getSimpleName());
		execAdv();
	}

	private void execAdv() {
		final Intent intent = getIntent();
		if (intent == null) {
			return;
		}

		final LinkType type = (LinkType) intent.getSerializableExtra(AdManager.EXTRA_TYPE);
		final String url = intent.getStringExtra(AdManager.EXTRA_URL);
		final AdManager am = AdManager.instance(this);
		mHandler.postDelayed(new Runnable() {
			public void run() {
				if (!am.executeAd(MainActivity.this, type, url)) {
					LogUtil.d(TAG, "failed to execute " + type + "," + url);
				}
			}
		}, 500);
	}

	private void loadDriftData() {
		DriftNetEngine engine = new DriftNetEngine();
		myUmengStaticstics.onGetDriftIcon(getApplicationContext());
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask = new NetTask(this, engine, 0);
		mNetTask.setListener(this);
		new Thread(mNetTask).start();
	}

	private void loadEscRecommendData() {
		EscRecommendNetEngine engine = new EscRecommendNetEngine();
		myUmengStaticstics.onGetEscRecommend(getApplicationContext());
		engine.setCacheStrategy(new CacheStrategy(true, CacheStrategy.THREE_HOUR));
		mNetTask2 = new NetTask(this, engine, 1);
		mNetTask2.setListener(this);
		new Thread(mNetTask2).start();
	}

	private boolean driftIsValidate(Drift drift) {
		if (drift == null) {
			return false;
		}
		long curr = System.currentTimeMillis();
		return curr >= drift.getStartTime() && curr <= drift.getEndTime();
	}

	private void enterLinkPage(Link link, String from) {
		if (LinkType.App == link.getType()) {
			Intent detail = new Intent(MainActivity.this, AppDetailActivity.class);
			detail.putExtra(AppDetailActivity.EXTRA_NAME, link.getTitle());
			detail.putExtra(AppDetailActivity.EXTRA_PKG, link.getUrl());
			detail.putExtra(AppDetailActivity.EXTRA_SOURCE,
					new ApkSource(from, link.getUrl(), null, null, null, null, null).toSourceString());
			startActivity(detail);
		} else if (LinkType.Cards == link.getType()) {
			if ("essential".equals(link.getUrl())) {
				startActivity(new Intent(MainActivity.this, PhoneEssentialActivity.class));
			} else {
				Intent detail = new Intent(MainActivity.this, CardPageActivity.class);
				detail.putExtra(CardPageActivity.EXTRA_TITLE, link.getTitle());
				detail.putExtra(CardPageActivity.EXTRA_PATH, link.getUrl());
				startActivity(detail);
			}
		} else if (LinkType.WebView == link.getType()) {
			Intent detail = new Intent(MainActivity.this, WebViewActivity.class);
			detail.putExtra(WebViewActivity.EXTRA_TITLE, link.getTitle());
			detail.putExtra(WebViewActivity.EXTRA_URL, link.getUrl());
			startActivity(detail);
		}
	}

	@Override
	protected void onDestroy() {
		mDestroyed = true;
		super.onDestroy();
		if (mNetTask != null) {
			mNetTask.cancel();
			mNetTask.setListener(null);
			mNetTask = null;
		}
		if (mNetTask2 != null) {
			mNetTask2.cancel();
			mNetTask2.setListener(null);
			mNetTask2 = null;
		}
		ImageLoader.getInstance().clearMemoryCache();
		getContentResolver().unregisterContentObserver(mContentObserver);
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main_menu, menu);

		ActionItemBadge.update(this, menu.findItem(R.id.action_download_management),
				getResources().getDrawable(R.drawable.title_download_btn_selector), ActionItemBadge.BadgeStyles.RED,
				mUnFinished);

//		ActionItemBadge.update(this, menu.findItem(R.id.action_management),
//				getResources().getDrawable(R.drawable.title_management_btn_selector), ActionItemBadge.BadgeStyles.RED,
//				mUpdateCount);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.action_download_management: {
			startActivity(new Intent(MainActivity.this, DownloadManagerActivity.class));
			return true;
		}

		case R.id.action_management: {
			startActivity(new Intent(this, UserCenterActivity.class));
			return true;
		}

		}
		return super.onOptionsItemSelected(item);
	}

	private boolean shouldShowEscRecommend() {
		if (mEscRecommend == null || mEscRecommendBannerImage == null) {
			return false;
		}
		// 如果已经安装或者已经在下载管理中存在，不展示
		Download dl = mEscRecommend.getDownload();
		if (dl != null) {
			if (PackageUtils.isPackageInstalled(this, dl.getPkgName())
					|| DownloadUtils.downloadExist(this, dl.getPkgName())) {
				return false;
			}
		} else {
			if (mEscRecommend.getLink() == null) {
				return false;
			}
		}

		long curr = System.currentTimeMillis();
		if (curr > mEscRecommend.getEndTime() || curr < mEscRecommend.getStartTime()) {
			return false;
		}
		if (mEscRecommend.getChance() <= 0) {
			return false;
		}
		if (mEscRecommend.getChance() >= 100) {
			return true;
		}

		int rnd = new Random().nextInt(100) + 1;
		return (rnd <= mEscRecommend.getChance());
	}

	private void showRecommendDialog() {

		mEscRecommendDialog = new EscRecommendDialog(this);
		String titleString;
		String confirmString;
		StatisticsAgent.onEvent(getApplicationContext(), new showEscRecommendEvent(new Gson().toJson(mEscRecommend)));
		myUmengStaticstics.onShowEscRecommend(getApplicationContext());
		if (mEscRecommend.getDownload() != null) {
			titleString = mEscRecommend.getDownload().getName();
			confirmString = "下载";
		} else {
			titleString = mEscRecommend.getLink().getTitle();
			confirmString = "查看";
		}

		mEscRecommendDialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				if (mEscRecommendDialog.exitFlag) {
					finish();
				}
			}
		});
		mEscRecommendDialog.showTitle(titleString)
				.showIcon(mEscRecommendBannerImage, System.currentTimeMillis(), new OnClickListener() {

					@Override
					public void onClick(View v) {
						mEscRecommendDialog.dismiss();
						StatisticsAgent.onEvent(getApplicationContext(), "escrecommendclickbanner");
						myUmengStaticstics.clickEscRecommendbanner(getApplicationContext());
						if (mEscRecommend.getDownload() != null) {
							Intent detail = new Intent(v.getContext(), AppDetailActivity.class);
							detail.putExtra(AppDetailActivity.EXTRA_NAME, mEscRecommend.getDownload().getName());
							detail.putExtra(AppDetailActivity.EXTRA_PKG, mEscRecommend.getDownload().getPkgName());
							detail.putExtra(AppDetailActivity.EXTRA_SOURCE,
									new ApkSource("escrecommend", mEscRecommend.getDownload().getPkgName(), null, null,
											null, null, null).toSourceString());
							startActivity(detail);
						} else {
							enterLinkPage(mEscRecommend.getLink(), "escrecommend");
						}
					}
				}).showButtonLeft("取消", new OnClickListener() {

					@Override
					public void onClick(View v) {
						StatisticsAgent.onEvent(getApplicationContext(), "escrecommendclickcancel");
						myUmengStaticstics.clickEscRecommendCancel(getApplicationContext());
						mEscRecommendDialog.dismiss();

					}
				}).showButtonRight(confirmString, new OnClickListener() {

					@Override
					public void onClick(View v) {
						mEscRecommendDialog.dismiss();
						StatisticsAgent.onEvent(getApplicationContext(), "escrecommendclickconfirm");
						myUmengStaticstics.clickEscRecommendConfirm(getApplicationContext());
						if (mEscRecommend.getDownload() != null) {
							addDownload(mEscRecommend.getDownload().getDlUrl(), mEscRecommend.getDownload().getName(),
									mEscRecommend.getDownload().getPkgName(),
									mEscRecommend.getDownload().getVersionName(),
									mEscRecommend.getDownload().getVersionCode(), mEscRecommend.getDownload().getMd5(),
									mEscRecommend.getDownload().getIconUrl(),
									new ApkSource("escrecommend", mEscRecommend.getDownload().getPkgName(), null, null,
											null, null, null).toSourceString());
						} else {
							enterLinkPage(mEscRecommend.getLink(), "escrecommend");
						}

					}
				}).show();
	}

	@Override
	public void onBackPressed() {
		long now = System.currentTimeMillis();

		if (mLastClickBackTime != 0 && Math.abs(now - mLastClickBackTime) < 2000) {
			super.onBackPressed();
		} else {
			Toast.makeText(this, "再按一次退出应用市场", Toast.LENGTH_SHORT).show();
			if (shouldShowEscRecommend()) {
				mLastClickBackTime = 0;
				showRecommendDialog();
			} else {
				mLastClickBackTime = now;
			}
			return;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mDriftView != null && driftIsValidate(mDrift)) {
			mDriftView.setVisibility(View.VISIBLE);
		} else if (mDriftView != null) {
			mDriftView.setVisibility(View.GONE);
		}
		String sk = getRandomSearchKey();
		if (!TextUtils.isEmpty(sk)) {
			TextView tv = findViewById(R.id.cust_home_search_textview);
			if (tv != null) {
//				tv.setText(getResources().getString(R.string.all_search_for) + Html.fromHtml(sk).toString());
				tv.setText(Html.fromHtml(sk).toString());

			}
		}

		AppMarketApplication app = (AppMarketApplication) getApplication();
		app.setAppIsRunning(true);
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	private void initDrawer() {
		mainDrawer = findViewById(R.id.activity_main_drawer);
		llMainSide = findViewById(R.id.ll_main_side);
		@SuppressLint("WrongViewCast") DrawerLayout.LayoutParams layoutParams = (DrawerLayout.LayoutParams) llMainSide.getLayoutParams();
		layoutParams.width = (int) (AndroidUtil.getScreenWidth(this) * 0.8);
		llMainSide.setLayoutParams(layoutParams);

		//侧滑筛选菜单
		homeMenuFragment = new HomeMenuFragment();
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		ft.replace(R.id.ll_main_side, homeMenuFragment);
		ft.commit();

		findViewById(R.id.cust_home_search).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, SearchActivity.class));
			}
		});

		findViewById(R.id.iv_home_download).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, DownloadManagerActivity.class));
			}
		});

		findViewById(R.id.iv_home_menu).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mainDrawer.openDrawer(Gravity.LEFT);
//				startActivity(new Intent(MainActivity.this, UserCenterActivity.class));
			}
		});
	}

	public void closeDrawer(){
		if (null!=mainDrawer){
			mainDrawer.closeDrawer(Gravity.LEFT);
		}
	}

	private void initTitle() {
		ActionBar actionBar = getActionBar();
		actionBar.setDisplayShowTitleEnabled(false);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayShowCustomEnabled(true);
		actionBar.setHomeButtonEnabled(false);

		actionBar.setCustomView(R.layout.cust_home_view);
		findViewById(R.id.cust_home_search).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				startActivity(new Intent(MainActivity.this, SearchActivity.class));
			}
		});

		findViewById(R.id.iv_home_menu).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				//TODO:显示菜单
				startActivity(new Intent(MainActivity.this, UserCenterActivity.class));
//				mainDrawer.openDrawer(Gravity.LEFT);
			}
		});
	}

	private void initTabStrip() {
		mTabStrip = findViewById(R.id.activity_main_tabstrip);
		mTabStrip.setViewPager(mViewPager);
		setTabsValue();
	}

	private void initViewPager() {
		mViewPager = findViewById(R.id.bank_view_pager);
		List<Pair<Fragment, String>> fragments = new ArrayList<Pair<Fragment, String>>();

		mFragmentDiscovery = new FragmentDiscovery();
		mFragmentRank = new FragmentRank();
		mFragmentGame = new FragmentGames();
		mFragmentApp = new FragmentApps();

		fragments.add(new Pair<Fragment, String>(mFragmentDiscovery, "发现"));
		fragments.add(new Pair<Fragment, String>(mFragmentRank, "排行"));
		fragments.add(new Pair<Fragment, String>(mFragmentGame, "游戏"));
		fragments.add(new Pair<Fragment, String>(mFragmentApp, "应用"));
		// cache all fragments
		mViewPager.setOffscreenPageLimit(fragments.size());
		mViewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), fragments));
	}

	/**
	 * 对PagerSlidingTabStrip的各项属性进行赋值。
	 */
	private void setTabsValue() {
		DisplayMetrics dm = getResources().getDisplayMetrics();
		// 设置Tab是自动填充满屏幕的
		mTabStrip.setShouldExpand(true);
		mTabStrip.setEnableDivider(false);
		// 设置Tab底部线的高度
		mTabStrip.setUnderlineHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0, dm));
		// 设置Tab Indicator的高度
		mTabStrip.setIndicatorHeight((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, dm));
		// 设置Tab标题文字的大小
		mTabStrip.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, dm));
		// 设置Tab Indicator的颜色
		mTabStrip.setIndicatorColor(Color.parseColor("#00ADFF"));
		// 设置选中Tab文字的颜色 (这是我自定义的一个方法)
		mTabStrip.setSelectedTextColor(Color.parseColor("#00ADFF"));
		// 取消点击Tab时的背景色
		mTabStrip.setTabBackground(0);
	}

	private static class MyAdapter extends FragmentPagerAdapter {

		private List<Pair<Fragment, String>> mFragments;

		public MyAdapter(FragmentManager fm, List<Pair<Fragment, String>> fragments) {
			super(fm);
			mFragments = fragments;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return mFragments.get(position).second;
		}

		@Override
		public int getCount() {
			return mFragments.size();
		}

		@Override
		public Fragment getItem(int position) {
			return mFragments.get(position).first;
		}
	}

	private String getRandomSearchKey() {
		NamedCacheStrategy cache = new NamedCacheStrategy("search_hotword");
		String content = cache.getContentFromCache();
		HotWordsResultData hw = new HotWordsResultData();
		if (!hw.parseResult(content)) {
			return null;
		}
		CardWords cardwords = hw.getCardWords();
		if (cardwords == null || cardwords.getWords() == null) {
			return null;
		}
		List<String> words = cardwords.getWords();
		if (words == null || words.isEmpty()) {
			return null;
		}
		return words.get(new Random().nextInt(words.size()));
	}

	private void loadEscRecommendBannerImage(final String imgurl, final int count) {
		if (mDestroyed) {
			return;
		}
		ImageLoader.getInstance().loadImage(imgurl, new SimpleImageLoadingListener() {
			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				if (count < 3) {
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							loadEscRecommendBannerImage(imgurl, count + 1);
						}
					}, 3000);
				}
			}

			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				mEscRecommendBannerImage = loadedImage;
			}
		});
	}

	private void loadDriftIcon(final Drift drift, final int count) {
		if (mDestroyed) {
			return;
		}
		if (!driftIsValidate(drift)) {
			return;
		}
		ImageLoader.getInstance().loadImage(drift.getIconUrl(), new SimpleImageLoadingListener() {
			@Override
			public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
				if (count < 3) {
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							loadDriftIcon(drift, count + 1);
						}
					}, 3000);
				}
			}

			@SuppressLint("NewApi")
			@SuppressWarnings("deprecation")
			@Override
			public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
				mDriftView = findViewById(R.id.activity_main_floatbtn);

				Drawable d = new BitmapDrawable(MainActivity.this.getResources(), loadedImage);
				if (android.os.Build.VERSION.SDK_INT >= 16) {
					mDriftView.setBackground(d);
				} else {
					mDriftView.setBackgroundDrawable(d);
				}
				mDriftView.setVisibility(View.VISIBLE);
				StatisticsAgent.onEvent(getApplicationContext(), new showDriftIconEvent(new Gson().toJson(drift)));
				myUmengStaticstics.onShowDriftIcon(getApplicationContext());
				mDriftView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						Link link = drift.getLink();
						myUmengStaticstics.onClickDriftIcon(getApplicationContext());
						StatisticsAgent.onEvent(getApplicationContext(), "clickdrifticon");
						enterLinkPage(link, "drift");
					}
				});
			}
		});
	}

	@Override
	public void onTaskRunSuccessful(int tag, BaseNetEngine engine) {
		if (tag == 0) { // 浮动按钮
			DriftResult result = (DriftResult) engine.getResultData();
			if (result.isOK()) {
				mDrift = result.getDrift();
				if (mDrift != null) {
					loadDriftIcon(mDrift, 1);
				}
			}
		} else if (tag == 1) { // 退出推荐
			EscRecommendResult result = (EscRecommendResult) engine.getResultData();
			if (result.isOK()) {
				mEscRecommend = result.getEscRecommend();
				if (mEscRecommend != null && !TextUtils.isEmpty(mEscRecommend.getBannerUrl())) {
					loadEscRecommendBannerImage(mEscRecommend.getBannerUrl(), 1);
				}
			}
		}
	}

	@Override
	public void onTaskRunError(int tag) {
		if (tag == 0) {// 浮动按钮
			if (mDriftDataRetryCount < 3) {
				mDriftDataRetryCount++;
				loadDriftData();
			}
		} else if (tag == 1) { // 退出推荐
			if (mEscRecommenDataRetryCount < 3) {
				mEscRecommenDataRetryCount++;
				loadEscRecommendData();
			}
		}
	}

	@Override
	public void onTaskRunCanceled(int tag) {

	}

	@Override
	public void onDownloadCreated(DownloadItem di) {
		super.onDownloadCreated(di);
		invalidateDownloadBadgeIfNeeded();
	}

	@Override
	public void onDownloadChanged(DownloadItem di) {
		super.onDownloadChanged(di);
		invalidateDownloadBadgeIfNeeded();
	}

	public void onDownloadRemoved(String id) {
		super.onDownloadRemoved(id);
		invalidateDownloadBadgeIfNeeded();
	}

	protected void onPackageInstalled(String pkgName) {
		invalidateDownloadBadgeIfNeeded();
		invalidateUpdateBadgeIfNeeded();
	}

	protected void onPackageUninstalled(String pkgName) {
		invalidateDownloadBadgeIfNeeded();
		invalidateUpdateBadgeIfNeeded();
	}

	private void invalidateDownloadBadgeIfNeeded() {
		int unFinished = DownloadUtils.getUnfinishedTaskCount(this);
		if (unFinished <= 0) {
			unFinished = Integer.MIN_VALUE;
		}
		if (unFinished != mUnFinished) {
			mUnFinished = unFinished;
			invalidateOptionsMenu();
		}
	}

	private void invalidateUpdateBadgeIfNeeded() {
		AppUpdateDatabase db = AppUpdateDatabase.getInstance(this);
		db.correctAppUpdatesDatas(this);
		int update = db.getCount(false);
		if (update <= 0) {
			update = Integer.MIN_VALUE;
		}

		if (update != mUpdateCount) {
			mUpdateCount = update;
			invalidateOptionsMenu();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQUEST_LOGIN_CODE || requestCode == REQUEST_LOGOUT_CODE) {
			if (null!=homeMenuFragment){
				homeMenuFragment.showUserInfo();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}
